package com.ytjj.qmyx.mall.service.impl;

import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.constants.SysConfigConstants;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.CopyWriterConfigUtil;
import com.ytjj.common.utils.OrderUtils;
import com.ytjj.common.utils.SysConfigUtil;
import com.ytjj.qmyx.mall.constants.ExpireTimeConstant;
import com.ytjj.qmyx.mall.constants.PayModeConstant;
import com.ytjj.qmyx.mall.enums.ActivityTypeEnums;
import com.ytjj.qmyx.mall.enums.ProductStatusEnums;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.request.CreateOrderRequest;
import com.ytjj.qmyx.mall.model.response.ProductSpecResponse;
import com.ytjj.qmyx.mall.service.CreateOrderService;
import com.ytjj.qmyx.mall.service.EvaluationProductService;
import com.ytjj.qmyx.mall.service.OrdersService;
import com.ytjj.qmyx.mall.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * 普通创建订单的方式
 *
 *
 * @version 1.0
 * 
 */
@Service("EVALUATION")
@Slf4j
@RefreshScope
public class OrdersEvaluationServiceImpl implements CreateOrderService<CreateOrderRequest> {

    @Autowired
    private EvaluationProductService evaluationProductService;

    @Autowired
    private OrdersService ordersService;

    @Resource
    private SysConfigUtil sysConfigUtil;

    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;

    @Resource
    private OrdersSpecMapper ordersSpecMapper;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private OrdersInfoMapper ordersInfoMapper;
    @Resource
    private DynamicMapper dynamicMapper;
    @Resource
    private OrderInfoDao orderInfoDao;
    @Resource
    private ProductService productService;
    @Resource
    private ProductMapper productMapper;
    @Autowired
    private RedisService redisService;
    @Value("${zeroBuySwitch:true}")
    private boolean zeroBuySwitch;
    @Value("${check.product.status:1}")
    private String checkProductStatus;//是否校验商品状态 1-校验  0-不需要校验


    @Override
    @Transactional
    public Integer createOrder(CreateOrderRequest request) {
        // 测评商品创建订单
        log.info("===零元测评===");
//        EvaluationProductSpecResponse productSpec = evaluationProductService.getProductSpecInfoById(request.getProductSpecId());
        ProductSpecResponse productSpec = productService.getProductSpecInfoById(request.getProductSpecId());
        if (Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.IS_STOCE_VERIFY)) > 0 && productSpec.getStock() <= 0) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.INSUFFICIENT_STOCK));
        }
        Product product = productMapper.selectByPrimaryKey(productSpec.getProductId());
        Optional.ofNullable(product)
                .orElseThrow(() -> new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.COMMODITY_NOT_EXIST)));

        if (checkProductStatus.equals("1")) {
            if (ProductStatusEnums.UP.getValue() != product.getStatus()) {
                throw new ApiException("商品已下架");
            }
        }
        if (Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.IS_STOCE_VERIFY)) > 0 && product.getStock() <= 0) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.INSUFFICIENT_STOCK));
        }
//        if (zeroBuySwitch) {
//            boolean checkBuyedResult = checkBuyedZeroEvaluation(request.getUserId());
//            if (!checkBuyedResult) {
//                throw new ApiException("您已购买过零元测评商品，不能继续购买！");
//            }
//        }
        //校验是否有在测评过程中的 和同一个商品是否购买过
//        boolean checkResult = doCheckUseProcess(request.getUserId());
//        if (!PayModeConstant.ORIGINAL_PRICE.equals(request.getFlag()) && !checkResult) {
//            throw new ApiException("您存在未完成的零元测评订单，不能继续购买！");
//        }
//        checkResult = doCheckBuyed(request.getUserId(), productSpec.getProductId());
//        if (!PayModeConstant.ORIGINAL_PRICE.equals(request.getFlag()) && !checkResult) {
//            throw new ApiException("您已购买过同商品的零元测评，不能继续购买！");
//        }

        redisService.set("product:info:" + product.getId(), com.gexin.fastjson.JSON.toJSONString(product));
        redisService.expire("product:info:" + product.getId(), 3 * 60);

        Integer isDirectBuy = 0;
        // 支付方式为 “直接购买” 则取出现价字段
        if(PayModeConstant.ORIGINAL_PRICE.equals(request.getFlag())){
            productSpec.setPrice(productSpec.getCurPrice());
            isDirectBuy = 1;
        }
        String orderParentNo = OrderUtils.getOrderCode(request.getUserId());//组合订单号
        //乘商品数量
        BigDecimal originalPrice_new = productSpec.getOriginalPrice();
        BigDecimal price_new = productSpec.getPrice();
        if (null != request.getProductSum() && request.getProductSum() > 1){
            originalPrice_new = productSpec.getOriginalPrice().multiply(BigDecimal.valueOf(request.getProductSum()));
            price_new = productSpec.getPrice().multiply(BigDecimal.valueOf(request.getProductSum()));
        }
        // 主订单
        Orders orders = ordersService.saveOrders(request.getUserId(), request.getTel(),
                originalPrice_new, price_new, request.getOrderSource(), request.getChannel(),0,orderParentNo);
        // 明细订单
        OrdersInfo ordersInfo = ordersService.saveOrdersInfo(orders.getId(), product.getId(), product.getProductName(), product.getProductImg(),
                productSpec.getPrice(), productSpec.getOriginalPrice(), product.getWarehouse(), product.getWarehouseName(),
                product.getWarehouseRule(), request.getSpecialId(), productSpec.getSkuSpec(), product.getBankerId(), productSpec.getId(),
                product.getActivityType(), null, product.getActivityMax(), product.getActivityMin(), product.getDescr(),isDirectBuy,request.getPageSourceV2()
                ,product.getId(),3,0, product.getCostPrice(), productSpec.getThreeSkuId(),request.getProductSum(),"",null);
        //todo 记录订单规格信息
        ProductSpec productSpecs = ordersSpecMapper.selectOrderSpec(request.getProductSpecId());
        ordersSpecMapper.insertOrderSpec(productSpecs.getSkuSpec(),orders.getId(),productSpecs.getPrice(),productSpecs.getOriginalPrice(),productSpecs.getCostPrice());
        return orders.getId();
    }

    /**
     * 校验用户是否购买过同商品的零元测评
     * @param userId
     * @param productId
     * @return true=未购买过  false=购买过
     */
    private boolean doCheckBuyed(Integer userId, Integer productId) {
        int zeroOrders = orderInfoDao.selectByUserIdAndProductAndStatus(productId, userId);
        if (zeroOrders <= 0) {
            return true;
        }
        return false;
    }

    /**
     * 校验用户是否购买过零元测评
     * @param userId
     * @return
     */
    private boolean checkBuyedZeroEvaluation(Integer userId) {
        int zeroOrders = orderInfoDao.selectByUserIdAndStatus(userId, ActivityTypeEnums.ZERO_EVALUATION.name());
        if (zeroOrders <= 0) {
            return true;
        }
        return false;
    }

    /**
     * 校验用户是否有正在使用中的零元测评订单，即动态未审核通过的订单
     * @param userId
     * @return true=没有正在使用中的  false=表示有未完成的测评订单，不能继续创建零元测评订单
     */
    private boolean doCheckUseProcess(Integer userId) {
        AtomicBoolean result = new AtomicBoolean(true);
        OrdersExample ordersExample = new OrdersExample();
        ordersExample.createCriteria().andUserIdEqualTo(userId).andIsPayEqualTo((byte)1).andOrderStatusIn(Arrays.asList("1", "2", "3"));
        List<Orders> ordersList = ordersMapper.selectByExample(ordersExample);
        if (CollectionUtils.isEmpty(ordersList)) {
            return result.get();
        }
        List<Integer> orderIds = ordersList.stream().map(Orders::getId).collect(Collectors.toList());
        OrdersInfoExample ordersInfoExample = new OrdersInfoExample();
        ordersInfoExample.createCriteria().andOrderIdIn(orderIds).andActivityTypeEqualTo("ZERO_EVALUATION");
        List<OrdersInfo> ordersInfoList = ordersInfoMapper.selectByExample(ordersInfoExample);
        if (CollectionUtils.isEmpty(ordersInfoList)) {
            return result.get();
        }
        List<Integer> orderInfoIds = ordersInfoList.stream().map(OrdersInfo::getId).collect(Collectors.toList());
        orderInfoIds.stream().forEach(item -> {
            DynamicExample example = new DynamicExample();
            example.createCriteria().andOrderInfoIdEqualTo(item);
            List<Dynamic> dynamicList = dynamicMapper.selectByExample(example);
            if (CollectionUtils.isEmpty(dynamicList)) {
                result.set(false);
                return;
            }else {
                List<Dynamic> checkFail = dynamicList.stream().filter(dy -> dy.getStatus() == 1 || dy.getStatus() == 0).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(checkFail)) {
                    result.set(false);
                    return;
                }
            }
        });
//        DynamicExample dynamicExample = new DynamicExample();
//        dynamicExample.createCriteria().andOrderInfoIdIn(orderInfoIds);//.andStatusNotIn(Arrays.asList((byte)1, (byte)0))
//        List<Dynamic> dynamicList = dynamicMapper.selectByExample(dynamicExample);
//        if (CollectionUtils.isEmpty(dynamicList)) {
//            result.set(false);
//            return result.get();
//        }
//        dynamicList.stream().forEach(item -> {
//            if (item.getStatus() == 2 || item.getStatus() == 3) {
//                result.set(false);
//                return;
//            }
//        });
        return result.get();
    }

    @Override
    public Integer cartCreateOrder(CreateOrderRequest request) {
        return null;
    }
}
